package org.zhangkun.jmsg.webserver.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;

import org.zhangkun.jmsg.webserver.bean.Cookie;
import org.zhangkun.jmsg.webserver.inter.Servlet;
import org.zhangkun.jmsg.webserver.server.Request;
import org.zhangkun.jmsg.webserver.server.Response;
import org.zhangkun.jmsg.webserver.util.MD5;


public class VCImg implements Servlet {

	public final static String STRS = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";

	private String randomStr(int size) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < size; i++) {
			int index = (int) (Math.random() * ((float) STRS.length()));
			sb.append(STRS.substring(index, index + 1));
		}
		return sb.toString();
	}

	private void paint(Graphics g, String str) {
		int woffset = 10;
		g.setFont(new Font("", Font.BOLD, 20));
		for (int i = 0; i < str.length(); i++) {
			String s = str.substring(i, i + 1);
			double angle = Math.random() * 10f
					* ((((int) Math.random() * 10f) % 2) == 0 ? -1 : 1);
			int fw = g.getFontMetrics().stringWidth(s);
			int w = (int) (Math.random() * 5f);
			int h = (int) (Math.random() * 10f);
			g.translate(woffset + fw / 2, h + g.getFontMetrics().getHeight()
					/ 2);
			Graphics2D g2d = (Graphics2D) g;
			g2d.rotate(Math.toRadians(angle));
			g.setColor(new Color((int) (Math.random() * 200f), (int) (Math
					.random() * 200f), (int) (Math.random() * 200f)));
			g.drawString(s, -w / 2, h / 2);
			g2d.rotate(-Math.toRadians(angle));
			g.translate(-(woffset + fw / 2), -(h + g.getFontMetrics()
					.getHeight() / 2));
			woffset += fw + w;
		}

		int size = (int) (Math.random() * 500f);

		for (int i = 0; i < size; i++) {
			g.setColor(new Color((int) (Math.random() * 200f), (int) (Math
					.random() * 200f), (int) (Math.random() * 200f)));
			int x = (int) (Math.random() * 100f);
			int y = (int) (Math.random() * 30);
			g.drawLine(x, y, x + 1, y + 1);
		}

	}

	@Override
	public void doRequest(Request rt, Response rs) throws Exception {
		// TODO Auto-generated method stub

		BufferedImage img = new BufferedImage(100, 30,
				BufferedImage.TYPE_4BYTE_ABGR);
		ByteArrayOutputStream aos = new ByteArrayOutputStream();
		String str = randomStr(5);
		paint(img.getGraphics(), str);
		ImageIO.write(img, "PNG", aos);
		rs.setContentType("image/png");
		rs.write(aos.toByteArray());
		Cookie c = new Cookie();
		c.setName("vc");
		c.setValue(MD5.getMD5(str.getBytes()));
		c.setCurrentOffestMinute(5);
		rs.addCookie(c);
	}

}
